#include "xtp_btn.h"
#include "system.h"
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

extern TaskHandle_t show_task_handle;


/**
 * 按键扫描，放在 Tick 钩子函数（滴答定时器函数）
 */
void key_scan(xtp_btn_t *btn)
{
    uint8_t btn_state = gpio_get_level(btn->port);

    btn->btn_buff = (btn->btn_buff << 1) | btn_state;

    /* 消抖成功 */
    if (btn->btn_buff == (uint16_t)0x0000)
    {
        btn->time_count++;
        btn->first_flag = 1;
        btn->total_flag = 1;
    }

    /* 总时间++ */
    if (btn->total_flag == 1)
    {
        btn->total_time_count++; /* 总时间++ */
    }

    /* 按下时间大于 1.5s 代表长按 */
    if ((btn->first_flag == 1) && (btn->time_count > 1500))
    {
        btn->result = LOOP_PRESS;
        btn->key_callback();
        xTaskNotifyGive(show_task_handle);
    }

    /* 按键松开状态 */
    if (btn->btn_buff == (uint16_t)0xffff)
    {
        if (btn->first_flag == 1) {
            btn->first_flag = 0;
            btn->time_count = 0;
            btn->click_count++;
        }
    }

    /* 总时间大于 0.5s 后，判断按键按下的次数 */
    if (btn->total_time_count > 500)
    {
        btn->key_callback();
        btn->click_count = 0;
        btn->total_time_count = 0; /* 清除总时间标志 */
        btn->total_flag = 0;       /* 清除总标志 */
        xTaskNotifyGive(show_task_handle);
    }
}

/**
 * 创建按键
*/
xtp_btn_t xtp_btn_create(gpio_num_t port, char *btn_name, void (*key_callback)())
{
    /* GPIO Config */
    gpio_reset_pin(port);
    gpio_set_direction(port, GPIO_MODE_INPUT);

    xtp_btn_t btn;

    btn.port = port;
    btn.result = NO_CLICK;
    strcpy(btn.btn_name, btn_name);
    btn.btn_buff = 0xffff;
    btn.first_flag = 0;
    btn.total_flag = 0;
    btn.time_count = 0;
    btn.total_time_count = 0;
    btn.press_time_num = 0;
    btn.click_count = 0;
    btn.key_callback = key_callback;

    return btn;
}